<template>
  <Modal :modelValue="modelValue" :title="title" @close="handleCloseDialog" @open="handleOpenDialog" width="635px"
    maxHeight="auto">
    <el-form ref="areaFormRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="上级行政区域" prop="pcode">
        <el-tree-select v-model="form.pcode" placeholder="选择上级行政区域" :data="parentAreaData" filterable check-strictly
          :props="{ children: 'children', label: 'name', value: 'ccode', hasChildren: 'has_children' }" />
      </el-form-item>
      <el-form-item label="行政区域名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入行政区域名称" />
      </el-form-item>
      <el-form-item label="拼音简写" prop="pinyin">
        <el-input v-model="form.pinyin" placeholder="请输入拼音简写" />
      </el-form-item>
      <el-form-item label="行政区域代码" prop="ccode">
        <el-input v-model="form.ccode" placeholder="请输入行政区域代码" />
      </el-form-item>
      <el-form-item label="顶级行政区域" prop="has_children">
        <el-radio-group v-model="form.has_children">
          <el-radio-button :value="1" label="是" />
          <el-radio-button :value="0" label="否" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.enabled">
          <el-radio-button :value="1" label="正常" />
          <el-radio-button :value="0" label="禁用" />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="modal-footer">
        <el-button type="primary" @click="handleSubmit" :loading="loading" :disabled="loading"> 确 定 </el-button>
        <el-button @click="handleCloseDialog"> 取 消 </el-button>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
defineOptions({
  name: "Area",
  inheritAttrs: false,
})
import AreaAPI, { AreaVO, AreaForm } from "@/api/area"
import { buildTree } from "@/utils";

// 定义接收的属性
interface Props {
  modelValue: boolean
  areaItem?: AreaVO
  title?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '表单',
})

// 自定义事件
const emit = defineEmits<{
  submit: [form: AreaForm]
  close: []
}>()

const areaFormRef = ref(ElForm)

const loading = ref(false)


const parentAreaData = ref<AreaVO[]>()

// 初始表单数据
const initialAreaForm = ref<AreaForm>({
  enabled: true,
  del: 0
})

const form = ref<AreaForm>({ ...initialAreaForm.value })

const rules = reactive({
  pcode: [{ required: true, message: "上级行政区域不能为空", trigger: "change" }],
  name: [{ required: true, message: "行政区域名称不能为空", trigger: "blur" }],
  ccode: [{ required: true, message: "行政区域代码不能为空", trigger: "blur" }],
})

const queryCondition: QueryCondition = {
  and: []
}

const getAreaTree = () => {
  //queryCondition.and = []
  // queryCondition.and?.push({ field: 'id', op: '=', value: 0 })
  AreaAPI.query(queryCondition).then((res) => {
    if (res.status == 200) {
      parentAreaData.value = buildTree(res.data, 'ccode', 'pcode')
    }
  })
}
onMounted(() => {
  getAreaTree()
})

const loadTreeData = (node, resolve) => {
  console.log(node)
  queryCondition.and = []
  if (node.level === 0) {
    queryCondition.and?.push({ field: 'id', op: '=', value: 0 })
  } else {
    queryCondition.and?.push({ field: 'pcode', op: '=', value: node.data.ccode })
  }
  AreaAPI.query(queryCondition).then((res) => {
    if (res.status == 200) {
      resolve(res.data)
    }
  })
}

/**
 * 打开部门弹窗
 */
const handleOpenDialog = () => {

}



/** 提交部门表单 */
const handleSubmit = () => {
  areaFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true
      if (form.value.id) {
        updateData()
      } else {
        saveData()
      }
    }
  })
}

const saveData = () => {
  loading.value = true
  form.value.id = form.value.ccode
  form.value.del = 0
  if (form.value.pcode === '0') {
    form.value.has_children = true
  }
  AreaAPI.add(form.value).then((res) => {
    if (res.status === 200) {
      ElMessage.success("新增成功")
      emit('submit', res.data)
    }
  }).finally(() => { loading.value = false })
}

const updateData = () => {
  loading.value = true
  AreaAPI.update(form.value).then((res) => {
    if (res.status === 200) {
      ElMessage.success("新增成功")
      emit('submit', res.data)
    }
  }).finally(() => { loading.value = false })
}
/** 关闭弹窗 */
const handleCloseDialog = () => {
  if (areaFormRef.value) {
    areaFormRef.value.resetFields()
    areaFormRef.value.clearValidate()
  }
  form.value = Object.assign({}, initialAreaForm.value)
  emit('close')
}



const getFormData = (areaId: number) => {
  AreaAPI.getFormData(areaId).then(res => {
    if (res.status === 200) {
      form.value = Object.assign({}, res.data)
    }
  })
}

//表单传递数据
watch(() => props.areaItem, (newVal: any, oldVal) => {
  if (newVal) {
    form.value = Object.assign({}, newVal)
    if (newVal.id) {
      getFormData(newVal.id)
    }
  }
}, { immediate: true, deep: true })

</script>
